﻿using Bussiness.DEV;
using Model;
using OPCAutomation;
using System;
using System.Collections.Generic;

namespace Bussiness
{
    public class OPC:IDEV
    {
        public Device Device { get; set; }
        public List<DevicePOI> DevicePOIList { get; set; }
        private OPCGroup _opcGroup;
        private OPCItem _opcItem;
        private OPCServer _opcServer = new OPCServer();
        private OPCBrowser _opcBrowser = null;

        public Result Connect()
        {
            Result result = new Result();

            try
            {
                if ((OPCServerState)_opcServer.ServerState == OPCServerState.OPCDisconnected)
                {
                    string[] arr = Device.IP.Split('_');
                    string serverName = arr[0];
                    string ip = arr[1];
                    _opcServer.Connect(serverName, ip);
                    if ((OPCServerState)_opcServer.ServerState == OPCServerState.OPCRunning)
                    {
                        _opcBrowser = _opcServer.CreateBrowser();
                        result.Success = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.Message;
            }

            return result;
        }

        public Result<List<Cfg_Field>> Read()
        {
            Result<List<Cfg_Field>> result = new Result<List<Cfg_Field>>();
            _opcServer.OPCGroups.RemoveAll();
            _opcGroup = _opcServer.OPCGroups.Add("NewGroup");
            _opcGroup.IsActive = true;
            foreach (var devPOI in DevicePOIList)
            {
                Cfg_Field cfg_Field = new Cfg_Field();
                cfg_Field.name = devPOI.DevPOIAlias;

                try
                {
                    _opcItem = _opcGroup.OPCItems.AddItem(devPOI.Address, 1);
                    object value;
                    object quality;
                    object timestamp;
                    _opcItem.Read(1, out value, out quality, out timestamp);
                    cfg_Field.value = value.ToString();
                    result.Success = true;
                    result.Data.Add(cfg_Field);
                }
                catch
                {

                }
            }

            return result;
        }
    }
}
